package jp.sourceforge.akjrcp.dropsomething;

import java.util.ArrayList;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;
import jp.sourceforge.akjrcp.dropsomething2.psp.PSPConvertTabBuilder2;
import jp.sourceforge.akjrcp.ui.PartAdapter2;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.part.ViewPart;

/**
 * This sample class demonstrates how to plug-in a new workbench view. The view
 * shows data obtained from the model. The sample creates a dummy model on the
 * fly, but a real implementation would connect to the model available either in
 * this or another plug-in (e.g. the workspace). The view is connected to the
 * model using a content provider.
 * <p>
 * The view uses a label provider to define how model objects should be
 * presented in the view. Each view can present the same model objects using
 * different labels and icons, if needed. Alternatively, a single label provider
 * can be shared between views in order to ensure that objects of the same type
 * are presented in the same way everywhere.
 * <p>
 */

public class DropsomethingView extends ViewPart {
	public static Log log = LogFactory.getLog(DropsomethingView.class);


	public static final String ID = DropsomethingView.class.getName();
	public static final String LAST_TAB=ID+"_lasttab";
	private CTabFolder tab;


	public static IWorkbenchPartSite viewSite;
	
	private IDropSomething[] something;
	private ViewPart viewPart;
	public void selectSomething(String title){
		//TODO id
		int s=tab.getItemCount();
		for (int i = 0; i < s; i++) {
			if(tab.getItem(i).getText().equals(title)){
				tab.setSelection(tab.getItem(i));
				break;
			}
		}
	}
	public void createPartControl(Composite root) {
		viewSite=(IWorkbenchPartSite) getSite();
		viewPart=this;
		tab = new CTabFolder(root, SWT.NONE);
		/*
		CTabItem tabItem1 = new CTabItem(tab, SWT.NONE);
		tabItem1.setText(Messages.getString("FLV_Convert"));
		tabItem1.setControl(new FLVConvertTab(this,tab,SWT.NONE));
		
		
		CTabItem tabItem2 = new CTabItem(tab, SWT.NONE);
		tabItem2.setText(Messages.getString("dropandsomething.textinsert"));
		tabItem2.setControl(new TextInsertTab(tab,SWT.NULL));
		*/
		try{
			something=findDropSomethings();
		
		for (int i = 0; i < something.length; i++) {
			something[i].createTab(this,tab);
			if(i==0){
				something[i].createControl(this, tab);//first one
			}
		}
		
		
		
		//for restore last tab selection
		String lastTab=Akj_betasPlugin.getDefault().getPluginPreferences().getString(LAST_TAB);
		if(!lastTab.equals("")){
		for (int i = 0; i <tab.getItemCount(); i++) {
			if(tab.getItem(i).getText().equals(lastTab)){
				tab.setSelection(i);//select last one;
				
				if(i>=0 && i<something.length){
						something[i].createControl(this, tab);
				}
			}
		}
		}
		
		//for tab selection
		tab.addSelectionListener(new SelectionListener(){
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {

			}

			@Override
			public void widgetSelected(SelectionEvent e) {
				int index=((CTabFolder)tab).getSelectionIndex();
				if(index>=0 &&index<something.length){
					something[index].createControl(viewPart, tab);
				}
			}});
		
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		//for save last tab selection
		this.getSite().getPage().addPartListener(new PartAdapter2(){
			public void partDeactivated(IWorkbenchPartReference partRef) {
				if(!tab.isDisposed()){
					try{
					CTabItem item=tab.getItem(tab.getSelectionIndex());
					if(item!=null && !item.isDisposed()){

					String value=item.getText();
				
					Akj_betasPlugin.getDefault().getPluginPreferences().setValue(LAST_TAB,value);
					}
					}catch(Exception e){e.printStackTrace();}
				}
			}
		}
		);
	}

	public String getCurrentTabId(){
		if(!tab.isDisposed()){
			try{
			CTabItem item=tab.getItem(tab.getSelectionIndex());
			if(item!=null && !item.isDisposed()){
				return item.getControl().getClass().getName();
			}
			}catch(Exception e){e.printStackTrace();}
		}
		return null;
	}
	
	public IDropSomething[] findDropSomethings(){
		String extensionName="somethings";
		ArrayList somethings = new ArrayList();

		IExtensionRegistry registry = Platform.getExtensionRegistry();
		IConfigurationElement[] elements =
	    registry.getConfigurationElementsFor("jp.sourceforge.akjrcp.akj_betas.Dropsomething");
	   
	    //Akj_betasPlugin.getDefault().getProcessPrinter().printOutput(""+elements.length);
	        for (int j = 0; j < elements.length; j++) {
	        	//log.info(elements[j].getName());
	            if (extensionName.equals(elements[j].getName())) {
	            	IDropSomething some;
					try {
						
						Object o=elements[j]
	                            .createExecutableExtension("class");
						//log.info(o.getClass().getName());
						some = (IDropSomething) o;
						somethings.add(some);
					} catch (CoreException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            	
	            }
	        }
	    
	     IDropSomething[] result = new IDropSomething[somethings.size()];
	    somethings.toArray(result);
	    sort(result);
	    return result;
	}
	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
	
	
	for (int i = 0; i < tab.getItemCount(); i++) {
		CTabItem item=tab.getItem(i);
		if(item.getControl()!=null){
		item.getControl().setFocus();//for init.
		}
	}
	tab.forceFocus();//must for focus tab.
	/*
	 * below didn't work now
	if(tab.getItemCount()>0){
		tab.getItem(0).getControl().setFocus();
	}else{
		tab.forceFocus();
		}*/
	}
//FFMpegConvertTabBuilder.class
	private static final Class[] orders=new Class[]{PSPConvertTabBuilder2.class,FFMpegConvertTabBuilder.class,PSPConvertTabBuilder.class,FLVConvertTabBuilder.class,MP3ConvertTabBuilder.class,MPEGConvertTabBuilder.class};
	
	public static void sort(IDropSomething[] somethings){
		for (int i = 0; i < somethings.length-1; i++) {
			for(int j=i+1;j<somethings.length;j++){
				int c1=countSortNumber(somethings[i]);
				int c2=countSortNumber(somethings[j]);
				if(c1<c2){
					IDropSomething tmp=somethings[i];
					somethings[i]=somethings[j];
					somethings[j]=tmp;
				}
			}
		}
	}
	private static int countSortNumber(IDropSomething something){
		int v=-1;
		for (int i = 0; i < orders.length; i++) {
			if(something.getClass().equals(orders[i])){
				v=orders.length-i;
				break;
			}
		}
		return v;
	}
}